package org.cocos2dx.javascript;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;
import com.nearme.game.sdk.GameCenterSDK;
import com.nearme.game.sdk.callback.*;
import com.nearme.game.sdk.common.model.ApiResult;
import com.nearme.game.sdk.common.model.biz.PayInfo;
import com.nearme.game.sdk.common.model.biz.ReportUserGameInfoParam;
import com.nearme.game.sdk.common.model.biz.ReqUserInfoParam;
import com.nearme.game.sdk.common.util.AppUtil;
import com.nearme.platform.opensdk.pay.PayResponse;
import com.opos.mobad.api.InitParams;
import com.opos.mobad.api.MobAdManager;
import com.opos.mobad.api.ad.BannerAd;
import com.opos.mobad.api.ad.NativeTempletAd;
import com.opos.mobad.api.ad.RewardVideoAd;
import com.opos.mobad.api.listener.IBannerAdListener;
import com.opos.mobad.api.listener.INativeTempletAdListener;
import com.opos.mobad.api.listener.IRewardVideoAdListener;
import com.opos.mobad.api.params.INativeTempletAdView;
import com.opos.mobad.api.params.NativeAdError;
import com.opos.mobad.api.params.NativeAdSize;
import com.opos.mobad.api.params.RewardVideoAdParams;

import android.support.constraint.Group;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class OPGameActivity {
	private static OPGameActivity instance;
	private AppActivity mAppActivity;
	private  OPGameActivity(){}
	private LinearLayout mAdContainer;
	private BannerAd mBannerAd;
	private String bannerId=Config.BANNER;
	private String rewardId=Config.RewardId;
	private String gameId=Config.AD;
	private String nativeId=Config.NativeExpressBannerId;
	private RewardVideoAd mRewardVideoAd;
	private LinearLayout nativeContainer;
    private INativeTempletAdView mINativeTempletAdView;
    private boolean bannerShowing=false;
	/**
	 * 原生模板广告对象
	 */
	private NativeTempletAd mNativeTempletAd;
	private boolean reLogin=false;
	public static OPGameActivity getInstance(){
		if(instance==null){
			instance=new OPGameActivity();
		}
		return instance;
	}
	public void init(AppActivity app){
		mAppActivity=app;
		InitParams initParams = new InitParams.Builder()
				.setDebug(true)
				//true 打开 SDK 日志，当应用发布 Release 版本时，必须注释掉这行代码的调用，或者设为 false
				.build();
		/**
		 * 调用这行代码初始化广告 SDK
		 */
		Log.d(Config.TAG, "initOPPOAD:InitParams");
		MobAdManager.getInstance().init(mAppActivity.getApplication(),gameId, initParams);
		initReward();
		initBanner();
        initNativeAd();
	}

	public void doLogin() {
		GameCenterSDK.getInstance().doLogin(mAppActivity, new ApiCallback() {
			@Override
			public void onSuccess(String arg0) {
				Log.d(Config.TAG, "oppo doLogin");
				doGetTokenAndSsoid();
			}
			@Override
			public void onFailure(String arg0, int arg1) {
				Log.d(Config.TAG, "oppo loginFail");
				Toast.makeText(mAppActivity,arg0,Toast.LENGTH_LONG).show();
				if(reLogin==false){
					reLogin=true;
					doLogin();
				}
			}
		});
	}
	public void exit(){
		GameCenterSDK.getInstance().onExit(mAppActivity,
				new GameExitCallback() {

					@Override
					public void exitGame() {
						// CP 实现游戏退出操作，也可以直接调用
						// AppUtil工具类里面的实现直接强杀进程~
						Log.d(Config.TAG, "CP 实现游戏退出操作，也可以直接调用");
						AppUtil.exitGameProcess(mAppActivity);
						if (null != mBannerAd) {
							/**
							 * 在退出页面时调用destroyAd来释放广告资源
							 */
							mBannerAd.destroyAd();
						}
						if(null!=mRewardVideoAd){
							mRewardVideoAd.destroyAd();
						}
					}
				});
	}

	public void getVerifiedInfo(final Map m) {
		GameCenterSDK.getInstance().doGetVerifiedInfo(new ApiCallback() {
			@Override
			public void onSuccess(String resultMsg) {
				try {
					//解析年龄age
					int age=Integer.parseInt(resultMsg);
					if (age < 18) {
						Log.d(Config.TAG, "已实名但未成年，CP开始处理防沉迷");
						m.put("isUnderage","true");
						WDNativePlatform.getInstance().loginFinish(m);
					} else {
						m.put("isUnderage","false");
						WDNativePlatform.getInstance().loginFinish(m);
						Log.d(Config.TAG, "已实名且已成年，尽情玩游戏吧~");
					}
				} catch (Exception e) {
					e.printStackTrace();
                    m.put("isUnderage","true");
                    WDNativePlatform.getInstance().loginFinish(m);
				}
			}

			@Override
			public void onFailure(String resultMsg, int resultCode) {
				if(resultCode == ApiResult.RESULT_CODE_VERIFIED_FAILED_AND_RESUME_GAME){
					m.put("isUnderage","true");
					WDNativePlatform.getInstance().loginFinish(m);
					Log.d(Config.TAG, "未实名");
				}else if(resultCode == ApiResult.RESULT_CODE_VERIFIED_FAILED_AND_STOP_GAME){
					Log.d(Config.TAG, "实名失败");
					exit();
				}
			}
		});
	}

	public void doGetTokenAndSsoid() {
		GameCenterSDK.getInstance().doGetTokenAndSsoid(new ApiCallback() {

			@Override
			public void onSuccess(String resultMsg) {
				try {
					JSONObject json = new JSONObject(resultMsg);
					String token = json.getString("token");
					String ssoid = json.getString("ssoid");
					Map m = new HashMap();
					m.put("userId", ssoid);
					m.put("result", "success");
					getVerifiedInfo(m);
				} catch (JSONException e) {
					e.printStackTrace();
					Log.d(Config.TAG, "doGetTokenAndSsoid"+e);
				}
			}

			@Override
			public void onFailure(String content, int resultCode) {
				Log.d(Config.TAG, "doGetTokenAndSsoid:onFailure"+content);
				if(reLogin==false){
					reLogin=true;
					doLogin();
				}
			}
		});
	}

	public void sendRoleInfo(int roleLv,String roleId,String realmId) {
		GameCenterSDK.getInstance().doReportUserGameInfoData(
				new ReportUserGameInfoParam(roleId, "default",roleLv, realmId, "九天揽月", "default", null), new ApiCallback() {

					public void onSuccess(String resultMsg) {
						Log.d(Config.TAG, "上传角色信息成功");
					}

					@Override
					public void onFailure(String resultMsg, int resultCode) {
						Log.d(Config.TAG, "上传角色信息失败："+resultMsg);
					}
				});

	}




	private void initReward(){
		mRewardVideoAd = new RewardVideoAd(mAppActivity, rewardId, new IRewardVideoAdListener() {
			@Override
			public void onAdSuccess() {
				Log.d(Config.TAG, "initOPPOAD:视频加载成功");
			}

			@Override
			public void onAdFailed(String s) {

			}

			@Override
			public void onAdFailed(int i, String s) {
				Map m1 = new HashMap();
				m1.put(Config.wdKeyVideoAdResult, Config.wdVideoAdFail);
				WDNativePlatform.getInstance().videoFinish(m1);
				Log.d(Config.TAG, "initOPPOAD:视频加载失败："+s);
			}

			@Override
			public void onAdClick(long l) {

			}

			@Override
			public void onVideoPlayStart() {

			}

			@Override
			public void onVideoPlayComplete() {

			}

			@Override
			public void onVideoPlayError(String s) {
				Map m1 = new HashMap();
				m1.put(Config.wdKeyVideoAdResult, Config.wdVideoAdFail);
				WDNativePlatform.getInstance().videoFinish(m1);
			}

			@Override
			public void onVideoPlayClose(long l) {
				Map m1 = new HashMap();
				m1.put(Config.wdKeyVideoAdResult, Config.wdVideoAdFail);
				WDNativePlatform.getInstance().videoFinish(m1);
				loadVideo();
			}

			@Override
			public void onLandingPageOpen() {

			}

			@Override
			public void onLandingPageClose() {

			}

			@Override
			public void onReward(Object... objects) {
				Map m1 = new HashMap();
				m1.put(Config.wdKeyVideoAdResult, Config.wdVideoAdSuccess);
				WDNativePlatform.getInstance().videoFinish(m1);
				Log.d(Config.TAG, "initOPPOAD:下发奖励");
				loadVideo();
			}
		});
		loadVideo();
	}
	private void loadVideo() {
		/**
		 * 调用loadAd方法请求激励视频广告;通过RewardVideoAdParams.setFetchTimeout方法可以设置请求
		 * 视频广告最大超时时间，单位毫秒；
		 */
		Log.d(Config.TAG, "initOPPOAD:请求加载激励视频");
		RewardVideoAdParams rewardVideoAdParams = new RewardVideoAdParams.Builder()
				.setFetchTimeout(3000)
				.build();
		mRewardVideoAd.loadAd(rewardVideoAdParams);
	}
	public void playVideo() {
		/**
		 * TODO 在播放广告时候，先调用isReady方法判断当前是否有广告可以播放；如果有、再调用showAd方法播放激励视频广告。
		 */
		if (mRewardVideoAd.isReady()) {
			mRewardVideoAd.showAd();
		}else {
			Map m1 = new HashMap();
			m1.put(Config.wdKeyVideoAdResult, Config.wdVideoAdFail);
			WDNativePlatform.getInstance().videoFinish(m1);
			loadVideo();
		}
	}

	private void initBanner() {
		mAdContainer = new LinearLayout(mAppActivity.getApplicationContext());
		mAdContainer.setOrientation(LinearLayout.VERTICAL);
		/**
		 * 构造 bannerAd
		 */
		mBannerAd = new BannerAd(mAppActivity, bannerId);
		/**
		 * 设置Banner广告行为监听器
		 */
		mBannerAd.setAdListener(new IBannerAdListener() {
			@Override
			public void onAdReady() {
				Log.d(Config.TAG, "initOPPOAD:banner加载成功");
			}

			@Override
			public void onAdClose() {

			}

			@Override
			public void onAdShow() {
				Log.d(Config.TAG, "initOPPOAD:banner展示成功");
			}

			@Override
			public void onAdFailed(String s) {
				Log.d(Config.TAG, "initOPPOAD:banner加载失败"+s);
			}

			@Override
			public void onAdFailed(int i, String s) {

			}

			@Override
			public void onAdClick() {

			}
		});
		/**
		 * 获取Banner广告View，将View添加到你的页面上去
		 *
		 */
		View adView = mBannerAd.getAdView();
		/**
		 * mBannerAd.getAdView()返回可能为空，判断后在添加
		 */
		if (null != adView) {
			/**
			 * 这里addView是可以自己指定Banner广告的放置位置【一般是页面顶部或者底部】
			 */
			FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
			params.gravity= Gravity.BOTTOM;
			mAdContainer.addView(adView);
			mAppActivity.addContentView(mAdContainer,params);
			mAdContainer.setVisibility(View.INVISIBLE);
			mAdContainer.setHorizontalGravity(Gravity.CENTER);
		}
		/**
		 * 调用loadAd()方法请求广告.
		 */
		// Timer _time=new Timer();
		// TimerTask _task=new TimerTask() {
		// 	@Override
		// 	public void run() {
		// 		mBannerAd.loadAd();
		// 	}
		// };
		// _time.scheduleAtFixedRate(_task,10,30000);
		mBannerAd.loadAd();
	}

	public void showBannerAd() {
		if(nativeContainer.getVisibility()==View.VISIBLE){
			return;
		}
        WDNativePlatform.getInstance().app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
				OPGameActivity.getInstance().mAdContainer.setVisibility(View.VISIBLE);
				OPGameActivity.getInstance().bannerShowing=true;
                Log.d(Config.TAG, "==========showBannerAd");
            }
        });
	}

	public void hideBannerAd() {
        WDNativePlatform.getInstance().app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                OPGameActivity.getInstance().mAdContainer.setVisibility(View.INVISIBLE);
                Log.d(Config.TAG, "==========hideBannerAd");
            }
        });
	}

	private void initNativeAd(){
        nativeContainer = new LinearLayout(mAppActivity.getApplicationContext());
        nativeContainer.setOrientation(LinearLayout.VERTICAL);
        FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity= Gravity.CENTER;
        mAppActivity.addContentView(nativeContainer,params);
        nativeContainer.setHorizontalGravity(Gravity.CENTER);
        mNativeTempletAd = new NativeTempletAd(mAppActivity, nativeId, null, new INativeTempletAdListener() {
            @Override
            public void onAdSuccess(List<INativeTempletAdView> list) {
                Log.d(Config.TAG, "onAdSuccess size=" + (null != list ?list.size() : "null"));
                if (null != list && list.size() > 0) {
                    if (null != mINativeTempletAdView) {
                        mINativeTempletAdView.destroy();
                    }
                    nativeContainer.setVisibility(View.INVISIBLE);
                    if (nativeContainer.getChildCount() > 0) {
                        nativeContainer.removeAllViews();
                    }
                    mINativeTempletAdView = list.get(0);
                    View adView = mINativeTempletAdView.getAdView();
                    if (null != adView) {
                        nativeContainer.addView(adView);
                        mINativeTempletAdView.render();
                    }
                }
            }

            @Override
            public void onAdFailed(NativeAdError nativeAdError) {
                Log.d(Config.TAG, "onAdFailed nativeAdError=" + (null != nativeAdError ?
                        nativeAdError.toString() : "null"));
            }

            @Override
            public void onAdClick(INativeTempletAdView iNativeTempletAdView) {

            }

            @Override
            public void onAdShow(INativeTempletAdView iNativeTempletAdView) {
                Log.d(Config.TAG, "onAdShow iNativeTempletAdView=" + (null != iNativeTempletAdView ?
                        iNativeTempletAdView : "null"));
            }

            @Override
            public void onAdClose(INativeTempletAdView iNativeTempletAdView) {
                Log.d(Config.TAG, "onAdClose iNativeTempletAdView=" + (null != iNativeTempletAdView ?
                        iNativeTempletAdView : "null"));
                /**
                 *当广告模板中的关闭按钮被点击时，广告将不再展示。INativeTempletAdView 也会被
                 Destroy，不再可用
                 */
                if (null != nativeContainer && nativeContainer.getChildCount() > 0) {
                    nativeContainer.removeAllViews();
                    nativeContainer.setVisibility(View.GONE);
                }
                mNativeTempletAd.loadAd();
                if(bannerShowing==true){
					bannerShowing=false;
                	showBannerAd();
				}
            }

            @Override
            public void onRenderSuccess(INativeTempletAdView iNativeTempletAdView) {
                Log.d(Config.TAG, "onRenderSuccess iNativeTempletAdView=" + (null !=
                        iNativeTempletAdView ? iNativeTempletAdView : "null"));
            }

            @Override
            public void onRenderFailed(NativeAdError nativeAdError, INativeTempletAdView iNativeTempletAdView) {
                Log.d(Config.TAG, "onRenderFailed nativeAdError=" + (null != nativeAdError ?
                        nativeAdError.toString() : "null") + ",iNativeTempletAdView=" + (null !=
                        iNativeTempletAdView ? iNativeTempletAdView : "null"));
            }
        });
        mNativeTempletAd.loadAd();
	}

	public void showNativeAd(){
		if(mAdContainer.getVisibility()==View.VISIBLE){
			hideBannerAd();
			bannerShowing=true;
		}else {
			bannerShowing=false;
		}
	    mAppActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                nativeContainer.setVisibility(View.VISIBLE);
            }
        });
    }
}